package com.topone.controller;

import com.topone.Converter.TcCouponForm2TcCouponConvert;
import com.topone.Enum.CouponEnum;
import com.topone.Exception.FanZoneException;
import com.topone.Exception.FanZoneServiceException;
import com.topone.Form.CouponForm;
import com.topone.Utils.CodeUntil;
import com.topone.Utils.KeyUntil;
import com.topone.Utils.ResultVOUntil;
import com.topone.Utils.ServiceUtils;
import com.topone.VO.ResultVO;
import com.topone.config.UploadConfig;
import com.topone.dataObject.CouponCategory;
import com.topone.dataObject.TcCoupon;
import com.topone.dto.BussinessDTO;
import com.topone.dto.TcCouponDTO;
import com.topone.service.CouponCategoryService;
import com.topone.service.TcCouponService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

/**
 * Created by Administrator on 2017/12/15,0015.
 */
@CrossOrigin
@RestController
@Slf4j
@RequestMapping("/seller/coupon")
public class SellerCouponController {

    @Autowired
    private CouponCategoryService couponCategoryService;

    @Autowired
    private TcCouponService couponService;

    @Autowired
    private TcCouponService tcCouponService;

    @Autowired
    private UploadConfig uploadConfig;

    @GetMapping("/list")
    public ResultVO<Map<String, Object>> list(@RequestParam(value = "couponName", required = false) String couponName,
                                              @RequestParam(value = "couponCode", required = false) String couponCode,
                                              @RequestParam(value = "status", required = false) Integer status,
                                              @RequestParam(value = "couponId", required = false) String couponId,
                                              @RequestParam(value = "businessId", required = false) String businessId,
                                              @RequestParam(value = "businessName", required = false) String businessName) {
        Map<String, Object> map = new HashMap<>();
        List<TcCouponDTO> couponList;
        TcCouponDTO tcCouponDTO = new TcCouponDTO();
        BussinessDTO bussinessDTO = new BussinessDTO();
        try {
            if (status != null) {
                tcCouponDTO.setCouponStatus(status);
            }
            if (StringUtils.isNotEmpty(couponId)) {
                tcCouponDTO.setCouponName(couponId);
            } else if (StringUtils.isNotEmpty(couponCode)) {
                tcCouponDTO.setCouponCode(couponCode);
            } else if (StringUtils.isNotEmpty(couponName)) {
                tcCouponDTO.setCouponName(couponName);
            } else if (StringUtils.isNotEmpty(businessId)) {
                bussinessDTO.setBussinessId(businessId);
            } else if (StringUtils.isNotEmpty(businessName)) {
                bussinessDTO.setBussinessName(businessName);
            }
            if (Objects.nonNull(tcCouponDTO) && StringUtils.isEmpty(bussinessDTO.getBussinessId())
                    && StringUtils.isEmpty(bussinessDTO.getBussinessName())) {
                couponList = couponService.queryCouponAndBusinessLikeList(tcCouponDTO);
            } else {
                couponList = couponService.findCouponByBusiness(bussinessDTO);
            }
        } catch (Exception e) {
            log.debug("商家查询优惠券失败{}", e.fillInStackTrace());
            return ResultVOUntil.error(1, e.fillInStackTrace().toString());
        }
        log.debug("-------------couponList-------------{}", ServiceUtils.toJson(couponList));
        map.put("couponList", couponList);
        log.info("查询商家后台优惠券信息成功:{}", map);
        return ResultVOUntil.success(map);
    }

    /**
     * 商品下架
     *
     * @param couponId
     * @param map
     * @return
     */
    @GetMapping("/off_sale")
    public ResultVO offSale(@RequestParam("couponId") String couponId,
                            Map<String, Object> map) {
        try {
            couponService.offSale(couponId);
            log.info("优惠券下架成功:", couponId);
            map.put("success", "下架成功");
        } catch (FanZoneException e) {
            log.info("优惠券下架失败:{}", couponId);
            return ResultVOUntil.error(1, couponId + "下架失败" + e.getMessage());
        }
        return ResultVOUntil.success(map);
    }

    /**
     * 商品上架
     *
     * @param couponId
     * @param map
     * @return
     */
    @GetMapping("/on_sale")
    public ResultVO onSale(@RequestParam("couponId") String couponId,
                           Map<String, Object> map) {
        try {
            couponService.onSale(couponId);
        } catch (FanZoneException e) {
            log.info("优惠券上架失败:{}" + couponId);
            return ResultVOUntil.error(1, couponId + "优惠券上架失败:" + e.getMessage());
        }
        log.info("优惠券上架成功,{}", couponId);
        map.put("success", "优惠券上架成功");
        return ResultVOUntil.success(map);
    }

    @GetMapping("/index")
    public ResultVO index(@RequestParam(value = "couponId", required = false) String couponId,
                          @RequestParam(value = "categoryId", required = false) String categoryId,
                          Map<String, Object> map) {

        if (!StringUtils.isEmpty(couponId)) {
            TcCoupon tcCoupon = couponService.findOne(couponId);
            map.put("tcCoupon", tcCoupon);
            log.info("查询优惠券成功{}", map);
        } else if (!StringUtils.isEmpty(categoryId)) {
            CouponCategory couponCategory = couponCategoryService.findOne(Integer.valueOf(categoryId));
            map.put("couponCategory", couponCategory);
            log.info("查询优惠券类型成功{}", map);
        } else {
            List<CouponCategory> categoryList = couponCategoryService.findAll();
            map.put("categoryList", categoryList);
            log.info("查询所有优惠券类型成功{}", map);
        }
        return ResultVOUntil.success(map);
    }

    @PostMapping("/save")
    @Transactional
    public ResultVO save(@RequestBody CouponForm couponForm) {
        Map<String, Object> map = new HashMap<>();
        TcCoupon tcCoupon;
        if (Objects.isNull(couponForm)) {
            log.error("【卖家端优惠券操作】 数据校验失败");
            return ResultVOUntil.error(1, "【卖家端优惠券保存操作】 数据校验失败");
        }
        log.debug("----------------couponForm-------------------{}", ServiceUtils.toJson(couponForm));

        try {
            tcCoupon = TcCouponForm2TcCouponConvert.convert(couponForm);
            tcCoupon.setCouponId(KeyUntil.getUniqueKey());
            tcCoupon.setCouponCode(CodeUntil.getTcCouponCode());
            log.debug("------tcCoupon----{}", ServiceUtils.toJson(tcCoupon));
            couponService.save(tcCoupon);
        } catch (Exception e) {
            log.error("【卖家端保存优惠券失败 " + e.fillInStackTrace());
            throw new FanZoneServiceException("卖家端保存优惠券失败" + e.fillInStackTrace());
        }
        map.put("success", "卖家端优惠券保存成功");
        return ResultVOUntil.success(map);
    }

    @GetMapping("/SellCouponByBusiness")
    public ResultVO findCoupons(@RequestParam(value = "bussinessId", required = false) String businessId,
                                @RequestParam(value = "bussinessName", required = false) String businessName) {
        Map<String, Object> map = new HashMap<>();
        BussinessDTO bussinessDTO = new BussinessDTO();
        if (StringUtils.isNotEmpty(businessId)) {
            bussinessDTO.setBussinessId(businessId);
        } else if (StringUtils.isNotEmpty(businessName)) {
            bussinessDTO.setBussinessName(businessName);
        } else {
            return ResultVOUntil.error(1, "参数不能为空:bussinessId=" + businessId + ",bussinessName=" + businessName);
        }
        try {
            List<TcCouponDTO> tcCouponList = tcCouponService.queryCouponByBusiness(bussinessDTO);
            map.put("tcCouponList", tcCouponList);
        } catch (Exception e) {
            log.debug("根据商家信息查询卖家所有优惠券，失败", e.fillInStackTrace());
            return ResultVOUntil.error(1, e.fillInStackTrace().toString());
        }

        log.info("根据商家信息查询卖家所有优惠券 成功:{}", map);
        return ResultVOUntil.success(map);
    }

    @GetMapping("/search")
    public ResultVO search(@RequestParam("name") String name) {
        Map<String, Object> map = new HashMap<>();
        List<TcCoupon> tcCouponDTOList = tcCouponService.queryList(name, CouponEnum.UP.getCode());
        log.info("根据优惠券名称查询:{}", tcCouponDTOList);
        map.put("tcCouponDTOList", tcCouponDTOList);
        return ResultVOUntil.success(map);
    }

    @PostMapping("/saveImage")
    public ResultVO saveCouponImages(@RequestParam("file") MultipartFile multipartFile) {
        Map<String, Object> map = new HashMap<>();

        //处理优惠券上传文件
        // 获取上传文件的路径
        String uploadCouponImgPath = uploadConfig.getCouponImgPath();
        // 截取上传文件的文件名
        String uploadCouponImgName = UUID.randomUUID().toString()
                .replace("-", "");
        ///截取上传文件的后缀
        String originalName = multipartFile.getOriginalFilename();
        String fileType = originalName
                .substring(originalName.indexOf('.') + 1, originalName.length());
        //文件全路径
        String filePath = uploadCouponImgPath + uploadCouponImgName + "." + fileType;
        String imgName = uploadCouponImgName + "." + fileType;
        FileOutputStream fos = null;
        FileInputStream fis = null;
        try {
            File file = new File(uploadCouponImgPath);
            if (!file.exists()) {   //商家图片路径不存在，创建路径
                file.mkdirs();
            }
            fis = (FileInputStream) multipartFile.getInputStream();
            fos = new FileOutputStream(new File(filePath));
            long size = fis.available();
            if (size > 104865760) {  //上传最大限制10M
                log.error("【后台添加优惠券】上传文件过大");
                return ResultVOUntil.error(1, "【后台添加优惠券】上传文件过大");
            }

            byte[] data = new byte[fis.available()];
            fis.read(data);
            fos.write(data);
        } catch (IOException e) {
            log.error("【后台添加优惠券】异常, {}", e.getStackTrace());
            return ResultVOUntil.error(1, "【后台添加优惠券】异常");
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                log.error("【后台添加优惠券】异常, {}", e.getStackTrace());
                return ResultVOUntil.error(1, "后台添加优惠券】异常");
            }
        }
        map.put("imgName", imgName);
        return ResultVOUntil.success(map);
    }
}
